package com.kongxiang.cubebit.ui.api;

import com.kongxiang.cubebit.base.common.dto.R;
import com.kongxiang.cubebit.ui.api.dto.VectorBatchGenerateRequest;
import com.kongxiang.cubebit.ui.api.dto.VectorSearchRequest;
import com.kongxiang.cubebit.ui.api.dto.VectorUpdateRequest;
import com.kongxiang.cubebit.vectordb.services.VectorStoreService;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/vector")
@Tag(name = "Vector API", description = "提供与向量相关的API接口")
public class VectorApiController {

    @Autowired
    private VectorStoreService vectorStoreService;

    /**
     * 批量生成向量化
     *
     * @param request 需要向量化的数据
     * @return 向量化结果
     * @see com.kongxiang.cubebit.ui.api.dto.VectorBatchGenerateRequest
     */
    @PostMapping("/add")
    @Schema(description = "批量生成向量化接口，用于将一批数据生成向量并存储到向量数据库中")
    public R<String> batchGenerateVectors(@RequestBody @Validated VectorBatchGenerateRequest request) {
        vectorStoreService.batchAdd(request.getData());
        return R.success("批量生成向量成功");
    }

    /**
     * 搜索向量
     *
     * @param request 搜索条件
     * @return 搜索结果
     * @see com.kongxiang.cubebit.ui.api.dto.VectorSearchRequest
     */
    @PostMapping("/search")
    @Schema(description = "向量搜索接口，根据查询条件返回最相似的K个向量结果")
    public R<List<Document>> searchVectors(@RequestBody @Validated VectorSearchRequest request) {
        return R.success(vectorStoreService.search(request.getQuery(), request.getK(),
                request.getThreshold()));
    }

    /**
     * 删除向量
     *
     * @param id 向量ID
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    @Schema(description = "删除向量接口，根据向量ID从向量数据库中删除指定的向量")
    public R deleteVector(@RequestParam String id) {
        vectorStoreService.delete(id);
        return R.success("删除向量成功");
    }

    /**
     * 更新向量
     *
     * @param request 更新数据
     * @return 更新结果
     * @see com.kongxiang.cubebit.ui.api.dto.VectorUpdateRequest
     */
    @PutMapping("/update")
    @Schema(description = "更新向量接口，根据向量ID和更新数据对向量数据库中的向量进行更新")
    public R updateVector(@Validated @RequestBody VectorUpdateRequest request) {
        vectorStoreService.update(request.getId(), request.getData());
        return R.success("更新向量成功");
    }
}